/*  Copyright (c) 2012 William Rogers and James Boud

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

using System;
using SlimDX;
using SlimDX.Direct3D11;
using JBBRXG11;

namespace JBBRXG11
{
    public enum BufferUsage
    {
        None = 0,
        WriteOnly = 8,
        Points = 64,
        StreamOut = 1024
    }

    /// <summary>
    /// Represents a list of 3D vertices to be streamed to the graphics device.
    /// </summary>
    public class VertexBuffer : IDisposable
    {
        GraphicsDevice device;
        SlimDX.Direct3D11.Buffer dxbuffer;
        int size; //What is this?...
        int vcount;
        int vsize;   // in bytes
        BufferUsage bufferusage;
        VertexDeclaration vdecl;

        internal SlimDX.Direct3D11.Buffer DX_Buffer { get { return dxbuffer; } }
        internal int StrideSize { get { return vsize; } }

        int findstructsize(Type t)
        {
            if (t.IsValueType)
            {
                if (t.IsPrimitive)
                {
                    if (t.Name == "Single") return 4;
                    else if (t.Name == "Double") return 8;
                    else if (t.Name == "Byte") return 1;
                    else if (t.Name == "SByte") return 1;
                    else if (t.Name == "UInt32") return 4;
                    else if (t.Name == "Int32") return 4;
                    else if (t.Name == "UInt16") return 2;
                    else if (t.Name == "Int16") return 2;
                    else if (t.Name == "Char") return 2;
                    else if (t.Name == "UInt64") return 8;
                    else if (t.Name == "Int64") return 8;
                }
                else if (!t.IsEnum) // Then only struct is left I hope
                {
                    int size = 0;
                    System.Reflection.FieldInfo[] fields = t.GetFields();
                    foreach (System.Reflection.FieldInfo fi in fields)
                    {
                        if (!fi.IsStatic)
                            size += findstructsize(fi.FieldType);
                    }
                    return size;
                }
            }
            throw new Exception("Can't resolve type or type not primitive");
        }

        //////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////// Constructors ////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////

        // NOTES:
        // In XNA 3.1 Usage can be writeonly, point and none
        //      Treating writeonly as CPU write, GPU read (dynamic)
        //      Treating none as just that - GPU access only (default).
        //      Point means that pointsprite data will be there, so the
        //                 driver should use main memory when emulating
        //                 Don't know how to do that, so returns exception
        //
        // To accomodate stream out buffers JBBRXG11 adds StreamOut as
        //     an option in its version of BufferUsage
        // Stream out seems to only be allowed as a BindFlag option if
        //     DX11 Usage is Default and CPU access is no access
        // For normal write and render use Usage DX11 Dynamic used
        // TODO:  Add extras for compute shader use
        // 
        // Regardless of setting CPU read is always available in this
        // class by using DX11 staging buffers as required
         
        void MakeBuffer()
        {
            BufferDescription bd;
            bd = new BufferDescription();
            bd.SizeInBytes = vsize * vcount;
            bd.StructureByteStride = vsize;
            bd.BindFlags = BindFlags.VertexBuffer;
            bd.Usage = ResourceUsage.Dynamic;
            bd.CpuAccessFlags = CpuAccessFlags.None;
            bd.OptionFlags = ResourceOptionFlags.None;

            if ((bufferusage & BufferUsage.Points) != 0)
            {
                throw new Exception("JBBRXG11 NYI: Can't do anything with point sprites");
            }
            if ((bufferusage & BufferUsage.StreamOut) != 0)
            {
                bd.BindFlags |= BindFlags.StreamOutput;
                bd.Usage = ResourceUsage.Default;
            }
            else if ((bufferusage & BufferUsage.WriteOnly) != 0)
            {
                bd.CpuAccessFlags = CpuAccessFlags.Write;
            }

            dxbuffer = new SlimDX.Direct3D11.Buffer(device.DX_Device, bd);
            GraphicsDeviceManager.GetGame(device).UserContentAdd(this);
        }

        /// <summary>
        /// Creates an instance of this object.
        /// </summary>
        /// <param name="graphicsDevice">The graphics device.</param>
        /// <param name="vertexType">The data type.</param>
        /// <param name="vertexCount">The number of vertices.</param>
        /// <param name="usage">Behavior options; it is good practice for this to
        /// match the createOptions parameter in the GraphicsDevice constructor.
        /// </param>
        public VertexBuffer(GraphicsDevice graphicsDevice, Type vertexType, int vertexCount, BufferUsage usage)
        {
            device = graphicsDevice;
            vdecl = null;
            vsize = findstructsize(vertexType);
            vcount = vertexCount;
            bufferusage = usage;
            MakeBuffer();
        }

        /// <summary>
        /// Creates an instance of this object.
        /// </summary>
        /// <param name="graphicsDevice">The graphics device.</param>
        /// <param name="vertexDeclaration">The vertex declaration, which describes
        /// per-vertex data.</param>
        /// <param name="vertexCount">The number of vertices.</param>
        /// <param name="usage">Behavior options; it is good practice for this to
        /// match the createOptions parameter in the GraphicsDevice constructor.
        /// </param>
        public VertexBuffer(GraphicsDevice graphicsDevice, VertexDeclaration vertexDeclaration, int vertexCount, BufferUsage usage)
        {
            //TODO: Buffer Constructor changes. This is correct. Check all classes.
            device = graphicsDevice;
            vdecl = vertexDeclaration;
            vsize = vdecl.GetVertexStrideSize();
            vcount = vertexCount;
            bufferusage = usage;
            MakeBuffer();
        }

        //////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////// Properties //////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Defines per-vertex data in a buffer.
        /// </summary>
        public VertexDeclaration VertexDeclaration { get { return vdecl; } }

        /// <summary>
        /// Gets the number of vertices.
        /// </summary>
        public int VertexCount { get { return vcount; } }

        /// <summary>
        /// Gets the state of the related BufferUsage enumeration.
        /// </summary>
        public BufferUsage BufferUsage { get { return bufferusage; } }

        //////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////// Methods /////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Sets vertex buffer data.  Reference page contains code sample.
        /// </summary>
        /// <param name="data">Array of data.</param>
        public void SetData<T>(T[] data) where T : struct
        {
            DataBox box = device.DX_Device_Context.MapSubresource(dxbuffer, MapMode.WriteDiscard, MapFlags.None);
            box.Data.WriteRange<T>(data);
            device.DX_Device_Context.UnmapSubresource(dxbuffer, 0);
        }


        public void GetData<T>(T[] data) where T : struct   // Not yet tested
        {
            int elementsize = findstructsize(data.GetType().GetElementType());
            if (elementsize * data.Length != vsize * vcount)
                throw new Exception("Array size is does not match buffer size");
            //if (startIndex < 0 || startIndex + elementCount > data.Length)
            //    throw new Exception("Index range does not lie within the data array");

            // Create a staging buffer to get CPU read access
            BufferDescription desc;
            SlimDX.Direct3D11.Buffer dxstaging;
            desc = dxbuffer.Description;
            desc.BindFlags = BindFlags.None;
            desc.CpuAccessFlags = CpuAccessFlags.Read;
            desc.Usage = ResourceUsage.Staging;
            desc.OptionFlags = ResourceOptionFlags.None;
            dxstaging = new SlimDX.Direct3D11.Buffer(device.DX_Device, desc);

            // Transfer data from the vertex buffer to the staging buffer
            // Note - CopyResource seems to require resources of exactly same size and depth, so we
            // must use CopySubresourceRegion to copy into the single mip level of the staging buffer
            device.DX_Device_Context.CopyResource(dxbuffer, dxstaging);
            //Game.GraphicsDevice.DX_Device_Context.CopySubresourceRegion(dxtexture, 0,
            //                                                            new ResourceRegion(0, 0, 0, desc.Width, desc.Height, 1),
            //                                                            dxstaging, 0, 0, 0, 0);

            // Read data from staging buffer
            DataBox box =device.DX_Device_Context.MapSubresource(dxstaging, MapMode.Read, MapFlags.None);
            box.Data.ReadRange<T>(data, 0, vsize * vcount / elementsize);
            Game.GraphicsDevice.DX_Device_Context.UnmapSubresource(dxstaging, 0);

            // Dispose of the unmanaged staging buffer structure
            dxstaging.Dispose();
        }


        public void Dispose()
        {
            dxbuffer.Dispose();
        }
    }
}

/*
    /// <summary>
    /// Sets vertex buffer data, specifying the start index and number of
    /// elements.
    /// </summary>
    /// <param name="data">Array of data.</param>
    /// <param name="startIndex">Index of the first element to set.</param>
    /// <param name="elementCount">Number of elements to set.</param>
    public void SetData<T>(T[] data, int startIndex, int elementCount)
    {
        throw new Exception("Not Yet Implemented");
    }

    /// <summary>
    /// Sets vertex buffer data, specifying the offset, start index, number of
    /// elements, and the vertex stride.
    /// </summary>
    /// <param name="offsetInBytes">Offset in bytes from the beginning of the
    /// buffer to the data.</param>
    /// <param name="data">Array of data.</param>
    /// <param name="startIndex">Index of the first element to set.</param>
    /// <param name="elementCount">Number of elements to set.</param>
    /// <param name="vertexStride">Stride, or size, of a vertex.</param>
    public void SetData<T>(int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride)
    {
        throw new Exception("Not Yet Implemented");
    }

    /// <summary>
    /// Gets a copy of the vertex buffer data.
    /// </summary>
    /// <param name="data">Array of data.</param>
    public void GetData<T>(T[] data)
    {
        throw new Exception("Not Yet Implemented");
    }

    /// <summary>
    /// Gets a copy of the vertex buffer data, specifying the start index and
    /// number of elements.
    /// </summary>
    /// <param name="data">Array of data.</param>
    /// <param name="startIndex">Index of the first element to get.</param>
    /// <param name="elementCount">Number of elements to get.</param>
    public void GetData<T>(T[] data, int startIndex, int elementCount)
    {
        throw new Exception("Not Yet Implemented");
    }

    /// <summary>
    /// Gets a copy of the vertex buffer data, specifying the starting offset,
    /// start index, number of elements, and vertex stride.
    /// </summary>
    /// <param name="offsetInBytes">Offset in bytes from the beginning of the
    /// buffer to the data.</param>
    /// <param name="data">Array of data.</param>
    /// <param name="startIndex">Index of the first element to get.</param>
    /// <param name="elementCount">Number of elements to get.</param>
    /// <param name="vertexStride">Size, in bytes, of an element in the vertex
    /// buffer.</param>
    public void GetData<T>(int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride)
    {
        throw new Exception("Not Yet Implemented");
    }

    /// <summary>
    /// Immediately releases the unmanaged resources used by this object.
    /// </summary>
    /// <param name="disposing">[MarshalAsAttribute(U1)] true to release both
    /// managed and unmanaged resources; false to release only unmanaged
    /// resources.</param>
    protected virtual void Dispose(bool value)
    {
        throw new Exception("Not Yet Implemented");
    }
}
*/